import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import  'rxjs/add/observable/forkJoin';
import { Park } from './park';
import { UserSettingProvider } from '../user-setting/user-setting';
import { SqliteHelperProvider } from '../sqlite-helper/sqlite-helper';

@Injectable()
export class ParkDataProvider {
  private readonly baseUrl: string = 'http://api.bmob.cn/1';
  private readonly httpHeaders : HttpHeaders = new HttpHeaders({
    'X-Bmob-Application-Id':'fafe6f75da68d65a8629f193dedb58c7',
    'X-Bmob-REST-API-Key':'5c1c0a59ce56a0c39b2f7ac7fe8b6970',
    'Content-Type':'application/json',
  });

  constructor(public http: HttpClient,
    private userSettingProvider: UserSettingProvider,
    private sqliteHelperProvider: SqliteHelperProvider) {
  }

  /**
   * 分页获取景区数据
   * @param num 
   * @param page 
   */
  getParks(num: number, page:number): Observable<Park[]>{
    let _params = new HttpParams()
    .set('limit', `${num}`)
    .set('skip', `${(page-1)*num}`);
    return this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,{headers:this.httpHeaders, params: _params}).map(_=>_['results']);
  }

  /**
   * 获取一条景区记录
   * @param objectId 
   */
  getPark(objectId: string): Observable<Park>{
    return this.http.get<Park>(`${this.baseUrl}/classes/parks/${objectId}`,{headers: this.httpHeaders});
  }

  /**
   * 获取记录条数
   */
  getCount(): Observable<number>{
    return this.http.get<number>(`${this.baseUrl}/classes/parks?limit=0&count=1`, {headers: this.httpHeaders}).map(data=>data['count']);
  }

  /**
   * 获取所有记录
   * @param total 记录总数
   */
  getAllParks(total: number): Observable<Park[][]>{
    let num = 500;
    let all: Observable<Park[]>[] = [];
    for (let index = 0; index < total / num; index++){
      let _params = new HttpParams()
      .set('limit', `${num}`)
      .set('skip', `${index*num}`);
    all[index] = this.http.get<Park[]>(`${this.baseUrl}/classes/parks`,{headers:this.httpHeaders, params: _params}).map(_=>_['results']);
    }
    return Observable.forkJoin(all);
  }

  /**
   * 缓存HTTP数据到本地
   */
  setParksToCache(): Promise<any>{
    return new Promise<any>((resolve, reject)=>{
      this.userSettingProvider.isRefreshData()
        .then(isRefresh => {
          console.log(`是否刷新：${isRefresh}`);
          if (isRefresh) {
            this.sqliteHelperProvider.createOrOpenDb() //打开或新建数据库
              .then(()=>{
                return this.sqliteHelperProvider.executeSql('DELETE FROM parks_lite', []);//清空原有数据库中的数据，即清空缓存
              })
              .then(()=>{
                return this.getCount().toPromise();//获取远端数据记录数
              })
              .then(total=>{
                return this.getAllParks(total).toPromise();//获取远端数据
              })
              .then(data=>{
                data.forEach(parks => {
                  console.log(`待加入数据：${parks.length}`);

                  let sql = 'INSERT INTO parks_lite (objectId, name, point)';
                  sql += ` SELECT '${parks[0].objectId}', '${parks[0].name}','${parks[0].point}'`;
                  for (let i = 1; i < parks.length; i++) {
                    sql += ` UNION ALL SELECT '${parks[i].objectId}', '${parks[i].name}', '${parks[i].point}'`;
                  }
                  this.sqliteHelperProvider.executeSql(sql, []);
                });//插入数据到数据库中，即建立缓存

                // data.forEach(parks =>{
                //   parks.forEach(park=>{
                //     let sql = 'INSERT INTO parks_lite (objectId, name, point)VALUES(?,?,?)';//实际要做4W+此插入操作，效率低
                //     let sql_params = [park.objectId, park.name, park.point];
                //     this.sqliteHelperProvider.executeSql(sql, sql_params);
                //   });
                // });
              })
              .then(()=>{
                this.userSettingProvider.setRefreshData();
              })
              .catch(err=>{
                console.log(err);
                reject(err)
              });
          }
        });
    });
  }

  /**
   * 从缓存中读取数据
   */
  getParksFromCache(): Promise<any> {
    return this.sqliteHelperProvider.createOrOpenDb()
      .then(()=>{
        return this.sqliteHelperProvider.executeSql('SELECT * FROM parks_lite',[]);
      });
  }
}
